#!/bin/bash
#/**********************************************************************
# Script Name  : schedulatore.sh                                                *
# Scope        :                                                                              *
#                                                                                                  *
#                                                                                                  *
# Function     :                                                                             *
#                                                                                                  *
# HISTORY                                                                                 *
#                                                                                                  *
# Version      DATE        Author       Description                          *
# -------   ----------    -----------   -------------------------------                 *
#     1.0   20-08-2014    S. Marsella    2.0.0                                 *
#/**********************************************************************
#-- Function Help
# P1 - prg che lo richiama
# P2 - syntax
# P3 - example1
# P4 - example2

function funHelp {
	echo "Programma di schedulazione file bonifici CBI:"
	echo "Il programma puo' essere eseguito nei seguenti modi:"
	echo "1: senza parametri"
	echo "   $0"
	echo "   la shell e' eseguita una sola volta"
	echo "2: indicando i secondi da attendere prima di riprovare"
	echo "   $0 10"
	echo "   la shell e' eseguita ogni 10 secondi"
	echo "3: HELP"
	echo "   $0 --help"
	echo "   Visualizza questo help"
}

#-- End function Help

#-- Main function ackCbiCheck
function ackCbiCheck {
	log "$FUNCNAME" "START"
	#-- Variable IN
	#-- Variable
	local _filesToCheck=$_DATI_DA_CBI_PATH"/*.run"
	
	log "$FUNCNAME" "[CHECH INTO]: $_DATI_DA_CBI_PATH/*.run"
	for f in $_filesToCheck
	do

	local _baseName=`basename $f`
	local __file="$f.out"
	if [ -e  $__file ] #per l'opzione -e consulta la legenda
	  then
	    log "$FUNCNAME" "[ EXIST ]: $__file"
	  else
	  	local _today=`date +%Y%m%d`
	  	local _lastModFileDate=`stat -c %w $f` #restituisce la data di unltima modifica es:"2014-08-18 15:24:02.877647900 +0200"	  	
	  	local _fileDate=`date -d "$_lastModFileDate" "+%Y%m%d"`
	  	if [ $_today -gt $_fileDate ]; then
	  		log "$FUNCNAME" "[ !EXIST ]: $__file"
			log "$FUNCNAME" "[ !ACTION]: $_fileDate less then today"
	  	elif [ $_today -eq $_fileDate ]; then
	  		log "$FUNCNAME" "[ !EXIST ]: $__file"
			log "$FUNCNAME" "[ CREATING ACK ATCBIH4 ]: $_fileDate equals today"
	  		
	  		if [[ $_baseName == ATCBIH4* ]]; then
	  			log "$FUNCNAME" "[ CALL ]: CBIEQH3.sh $f..."
	  			log "$FUNCNAME"  "sh $_SHELL_PATH/CBIEQH3.sh $f"
				#sh $_SHELL_PATH/CBIEQH3.sh $f #DA DECOMMENTARE
	  			log "$FUNCNAME" "[ RETURN ]: CBIEQH3.sh $f..."
	  			#se CBIEQH3 allora simulo il corretto esito del bonifico creando CBIEQH6
	  			local _esitoBonifico=$(xmlStarlet sel -N $ATCBIH4_X -N $ATCBIH4_DPSR -N $ATCBIH4_CPSR -t -v "$ATCBIH4_ESITO_BON" $f)
	  			log "$FUNCNAME" "$_esitoBonifico"
	  			if [ "$_esitoBonifico" == "ACTC" ]; then
	  				replaceTemplateATCBIH6 $_baseName $f
	  			fi	  				  			
	  		elif [[ $_baseName == ATCBIH6* ]]; then
	  			log "$FUNCNAME" "[ CALL ]: CBIEQH5.sh $f..."
	  			log "$FUNCNAME" "sh $_SHELL_PATH/CBIEQH5.sh $f"
	  			#sh $_SHELL_PATH/CBIEQH5.sh $f #DA DECOMMANTARE
	  			log "$FUNCNAME" "[ RETURN ]: CBIEQH5.sh $f..."
	  		else 
	  			log "$FUNCNAME" "[ ERROR ]: Not found shell to call"
	  		fi	  		
	  	else
	  		log "$FUNCNAME" "[ ERROR ]: No action to run"
	  	fi
	fi	
	done
	log "$FUNCNAME" "END"
}
#-- End function ackCbiCheck


function replaceTemplateATCBIH4 {
	log "$FUNCNAME" "START"
	local _baseName=${1}
	local f=${2}
	
	local _newBaseFileName=${_baseName/CBIATH1/ATCBIH4} #Nome del nuovo file ack
	log "$FUNCNAME" $_newBaseFileName

        local outputxml=$(< $_ACK_TEMPLATES"/"$_TEMPLATE_H4)
	
	local _fileNm=${_newBaseFileName/ATCBIH4/ATCBIH3} 
	outputxml=$( echo ${outputxml} | xmlStarlet ed -N $ATCBIH4_X -N $ATCBIH4_DPSR -N $ATCBIH4_CPSR -u "$ATCBIH4_ESITO_FILENM" -v $_fileNm )
	##################   substIntoATCBIH4FromCBIATH1.csv  ###############################
	# Eseguo le sostituzioni in base al file di configurazione                                                                        #
	# Il file deve contenere:                                                                                                                           #
	# xPath del campo del file H4 da sostituire , @xPath (del valore nel file H1) o valore da sostituire       #
	# Per indicare un xPath nel file H1 bisogna inserirlo preceduto da @                                                    #
	# ES: root/field1/field2,@root/field3                                                                                                         #
	#        root/field1/field2,newValue                                                                                                            #
	#################################################################################
	while IFS=, read xPathH4 value typeFormat
	do
	    if [[ $xPathH4 != "#"* && ! -z "$xPathH4" && ! -z $value ]]; then
	      local _valueToReplace = $value
	      if  [[ $value == @* ]]; then
		local length=${#value}
		local xPath=${value:1:$length}
		_valueToReplace=$( xmlStarlet sel -N $CBIATH1_X -N $CBIATH1_NS2 -t -v "$xPath" $f ) #Seleziono il valore dall'xPath
		log "$FUNCNAME" "typeFormat[$typeFormat]"
		if [[ ! -z "$typeFormat" && $typeFormat == "?DATE?"* ]]; then
			local _length=${#typeFormat}
			local _format=${typeFormat:6:$_length}
			_valueToReplace=`date -d "$_valueToReplace" "$_format"`
		fi
	      elif [[ $value == "@[]"* ]]; then
			local _length=${#value}
			local _formula=${value:3:$_length}
			_valueToReplace=$( eval "$_formula" )
	      fi
	      log "$FUNCNAME" "xPath[$xPath]:$_valueToReplace"
	      log "$FUNCNAME" "[ $_valueToReplace ] -> $xPathH4"
	      outputxml=$( echo ${outputxml} | xmlStarlet ed -N $ATCBIH4_X -N $ATCBIH4_DPSR -N $ATCBIH4_CPSR -u "$xPathH4" -v $_valueToReplace )		
           fi
	done < substIntoATCBIH4FromCBIATH1.csv	
	
	local _rndEsito=$[ 1 + $[ RANDOM % 10 ]]
	
	if [ $_rndEsito -lt 5 ]; then
		log "$FUNCNAME" "[ RESULT ]: RJCT"
		outputxml=$( echo ${outputxml} | xmlStarlet ed -N $ATCBIH4_X -N $ATCBIH4_DPSR -N $ATCBIH4_CPSR -u "$ATCBIH4_ESITO_BON" -v "RJCT" )
	else 
		log "$FUNCNAME" "[ RESULT ]: ACTC "	  				  		
	fi  
	
	echo $outputxml > $_DATI_DA_CBI_PATH"/"$_newBaseFileName".run"
	
	log "$FUNCNAME" "[ CREATED ACK ]: "$_DATI_DA_CBI_PATH"/"$_newBaseFileName
	log "$FUNCNAME" "END"
}



function replaceTemplateATCBIH6 {	
	log "$FUNCNAME" "START"
	local _baseName=${1}
	local f=${2}
	
	local _newBaseFileName=${_baseName/ATCBIH4/ATCBIH6} #Nome del nuovo file ack

        local outputxml=$(< $_ACK_TEMPLATES"/"$_TEMPLATE_H6)

	local _fileNm=${_newBaseFileName/ATCBIH6/ATCBIH5} 
	outputxml=$( echo ${outputxml} | xmlStarlet ed -N $ATCBIH6_X -N $ATCBIH6_DPSR -N $ATCBIH6_CPSR -u "$ATCBIH6_ESITO_FILENM" -v $_fileNm )

	##################   substIntoATCBIH6FromCBIATH4.csv  ###############################
	# Eseguo le sostituzioni in base al file di configurazione                                                                        #
	# Il file deve contenere:                                                                                                                           #
	# xPath del campo del file H6 da sostituire , @xPath (del valore nel file H4) o valore da sostituire       #
	# Per indicare un xPath nel file H4 bisogna inserirlo preceduto da @                                                    #
	# ES: root/field1/field2,@root/field3                                                                                                         #
	#        root/field1/field2,newValue                                                                                                            #
	#################################################################################
	while IFS=, read xPathH6 value typeFormat
	do
	    if [[ $xPathH6 != "#"* && ! -z "$xPathH6" && ! -z $value ]]; then
	      local _valueToReplace=$value
	      if  [[ $value == "@/"* ]]; then
		local length=${#value} 
		local xPath=${value:1:$length}
		_valueToReplace=$( xmlStarlet sel -N $ATCBIH4_X -N $ATCBIH4_DPSR -N $ATCBIH4_CPSR -t -v "$xPath" $f ) #Seleziono il valore dall'xPath
		log "$FUNCNAME" "typeFormat[$typeFormat]"
		if [[ ! -z "$typeFormat" && $typeFormat == "?DATE?"* ]]; then
			local _length=${#typeFormat}
			local _format=${typeFormat:6:$_length}
			_valueToReplace=`date -d "$_valueToReplace" "$_format"`
		fi
	      elif [[ $value == "@[]"* ]]; then
			local _length=${#value}
			local _formula=${value:3:$_length}
			_valueToReplace=$( eval "$_formula" )
	      fi
	      log "$FUNCNAME" "xPath[ $xPath ]:$_valueToReplace"
	      outputxml=$( echo ${outputxml} | xmlStarlet ed -N $ATCBIH6_X -N $ATCBIH6_DPSR -N $ATCBIH6_CPSR -u "$xPathH6" -v $_valueToReplace )	
	      log "$FUNCNAME" "[ $_valueToReplace ] -> $xPathH6"	
           fi
	done < substIntoATCBIH6FromCBIATH4.csv	

	echo $outputxml	> $_DATI_DA_CBI_PATH"/"$_newBaseFileName
	log "$FUNCNAME" "creato il file di ack "$_DATI_DA_CBI_PATH"/"$_newBaseFileName
	log "$FUNCNAME" "END"
}

#-- Start function log
function log {
	echo "[ `date +%Y%m%d-%H:%M:%S` ${1} ]: ${2}"
}
#-- End function log

#-- Main function filesForCbiCheck
function filesForCbiCheck {
	log "$FUNCNAME" "START"
	#-- Variable IN
	#-- Variable
	local _filesToCheck=$_DATI_PER_CBI_PATH"/*"
	log "$FUNCNAME" "[ CHECK INTO]: $_DATI_PER_CBI_PATH/*"
	for f in $_filesToCheck
	do
	 local _baseName=`basename $f`
	 local __file=$_DATI_PER_CBI_PATH"/."$_baseName
	 if [ -e  $__file ] #per l'opzione -e consulta la legenda
	  then
	    #il file check esiste, non faccio niente
	    log "$FUNCNAME" "[ EXIST ]: $__file"
	  else
	  	#il file check non esiste, genero il file di ack fittizio
	  	local _today=`date +%Y%m%d`
	  	local _lastModFileDate=`stat -c %w $f` #restituisce la data di ultima modifica es:"2014-08-18 15:24:02.877647900 +0200"	  	
	  	local _fileDate=`date -d "$_lastModFileDate" "+%Y%m%d"`
	  	if [ $_today -gt $_fileDate ]; then
	  		log "$FUNCNAME" "[ !EXIST ]: $__file.out"
			log "$FUNCNAME" "[ !ACTION]: $_fileDate less then today"
	  	elif [ $_today -eq $_fileDate ]; then
	  		log "$FUNCNAME" "[ !EXIST ]: $__file.out"
			log "$FUNCNAME" "[ CREATING ACK ATCBIH4 ]: $_fileDate equals today"	  
	  		
	  		if [[ $_baseName == CBIATH1* ]]; then
	  			replaceTemplateATCBIH4 $_baseName $f
				#echo "CBI simulation check OK" > $__file
	  		else 
	  			log "$FUNCNAME" "[ ERROR ]: Not found shell to call"
	  		fi	  		
	  					  		
	  	else
	  		log "$FUNCNAME" "[ ERROR ]: No action to run"
	  	fi
	fi
	done
	log "$FUNCNAME" "END"
}
#-- End function filesForCbiCheck

#-- Main task

#-- Load function
#typeset -fx filesForCbiCheck ackCbiCheck funHelp
exp='^[0-9]+$'
#Carico il file delle proprietà
. scheduler.properties #lo spazio dopo il punto è importante; le variabili del file sono accessibili con $

if [ $# -eq 0 ]; then	
	if [ -t 1 ] ; then clear; fi
	filesForCbiCheck
	sleep 1
	ackCbiCheck
elif [ $# -eq 1 ]; then
	if [ "${1}" == "--help" ]; then
   	funHelp ${0}
  elif [[ ${1} =~ $exp ]]; then	   	
	   while true
			do
		 		if [ -t 1 ] ; then clear; fi
     		     		log "$0" "START CHECK"
     				filesForCbiCheck 
				sleep 1
	   			ackCbiCheck
				log "$0" "END CHECK"
	   			sleep ${1}
	   	done
	else 
		log "$FUNCNAME" "For help try: $0 --help"
	fi
else 
	log "$FUNCNAME" "For help try: $0 --help"
fi

#-- End task

#Per eseguire lo script come daemon eseguire il seguente comando
#nohup ./schedulatore.sh 30 > schedulatore.log &

# -b filename   Block special file
# -c filename   Special character file
# -d directoryname  Check for directory existence
# -e filename   Check for file existence
# -f filename   Check for regular file existence not a directory
# -G filename   Check if file exists and is owned by effective group ID.
# -g filename   true if file exists and is set-group-id.
# -k filename   Sticky bit
# -L filename   Symbolic link
# -O filename   True if file exists and is owned by the effective user id.
# -r filename   Check if file is a readable
# -S filename   Check if file is socket
# -s filename   Check if file is nonzero size
# -u filename   Check if file set-ser-id bit is set
# -w filename   Check if file is writable
# -x filename   Check if file is executable
#Vedi esempi su
#http://blog.arturu.it/2012/04/01/linux-shell-script-principianti-iniziare-programmare-con-la-shell
